package com.dmbjz.controller;

import com.dmbjz.entity.Comment;
import com.dmbjz.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/** MongoRepository 操作数据案例  */
@RestController
@RequestMapping("repository")
public class HelloRepository {


    @Autowired
    private UserRepository userRepository;


    /*保存*/
    @RequestMapping("save")
    public void saveComment(){

        List<Comment> tempList = new ArrayList<>(3);
        tempList.add(new Comment("1","今天天气还行","dmbjz",new Date(),"游客A", LocalDateTime.now(),200,200,"1"));
        tempList.add(new Comment("2","手机今天欠费","dmbjz",new Date(),"游客B", LocalDateTime.now(),80,200,"1"));
        tempList.add(new Comment("3","你打算在今天干嘛","dmbjz",new Date(),"游客C", LocalDateTime.now(),170,200,"1"));
        tempList.add(new Comment("4","我觉得明晚不错","cctv",new Date(),"游客D", LocalDateTime.now(),100,200,"1"));
        tempList.add(new Comment("5","要学习知识","acfun",new Date(),"游客E", LocalDateTime.now(),100,200,"1"));
        userRepository.saveAll(tempList); //批量保存

        Comment comment = new Comment("额外添加的数据","acfun",new Date(),"游客Z", LocalDateTime.now(),500,30,"1");
        userRepository.save(comment);   //保存单个数据

    }


    /*更新*/
    @RequestMapping("update")
    public void updateComment(){

        //单个更新，先查询再更新数据，需要依赖主键ID字段
        Optional<Comment> findComment = userRepository.findById("4");
        findComment.ifPresent(info->{
            info.setNickname("dmbjz_new");
            info.setContents("MongoRepository更新操作");
            info.setLikenum(999);
            userRepository.save(info);
        });

        //批量更新,需要依赖主键ID字段
        List<Comment> upList = new ArrayList<>(2);
        Comment temp = new Comment().setId("1").setContents("今天天气不行");
        Comment temp2 = new Comment().setId("2").setContents("今天手机交话费了");
        upList.add(temp);
        upList.add(temp2);
        userRepository.saveAll(upList);

    }


    /*删除*/
    @RequestMapping("del")
    public void deleteCommentById(){

        //无论是 delete 方法还是 deletAll 方法，其内部参数都需要携带主键ID字段，否则会在 getByIdQuery() 中抛出异常，因此实际使用 deleteById 方法即可
        userRepository.deleteById("3");      //删除 id = 3 的数据

    }


    /*查询*/
    @RequestMapping("find")
    public void findCommentList(){

        //查询全部数据
        List<Comment> findList = userRepository.findAll();
        findList.forEach(System.out::println);


        //根据ID查询
        Optional<Comment> info = userRepository.findById("1");
        info.ifPresent(a->
             System.out.println("根据ID查询到的数据:"+ a.getId())
        );


        /*
         * 精确查询
         *   查询所有结果为 userid为dmbjz + likenum等于100 的数据
         */
        Comment comment = new Comment();
        comment.setUserid("dmbjz");
        comment.setLikenum(100);
        Example<Comment> userExample = Example.of(comment);
        List<Comment> comments = userRepository.findAll(userExample);
        comments.forEach(System.out::println);



        /*
         *  模糊查询
         *     缺点：只能对所有条件字段统一进行某种特定的搜索，但数值类型只能进行精确匹配
         *     例：查询 userid包含dmbjz + likenum等于20 + content包含“还行”的数据
         */
        System.out.println("========== 模糊搜索案例 START ============");

        ExampleMatcher matcher = ExampleMatcher.matching()                                      //构建匹配器
                                    .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                                    .withIgnoreCase(true);                                      //改变默认大小写忽略方式：忽略大小写
        Comment comment2 = new Comment();
        comment2.setUserid("dmbjz");
        comment2.setLikenum(20);               //数值类型只能精确查询
        comment2.setContents("还行");
        Example<Comment> userExample2 = Example.of(comment2, matcher);
        List<Comment> userList = userRepository.findAll(userExample2);
        System.out.println(userList);

        System.out.println("========== 模糊搜索案例 END ============");


        //查询数据总量
        long count = userRepository.count();
        System.out.println("springboot集合中当前文档总数为: " + count);


        /*
         *  分页查询
         */
        System.out.println("========== 分页查询 START ============");
        Sort sort = Sort.by(Sort.Direction.DESC, "age");            //根据Age字段倒序
        Pageable pageable = PageRequest.of(0, 10, sort);            //创建分页对象,参数: 当前页索引(第1页index 0，第二页index 1....)、数据显示数、排序

        ExampleMatcher pageMatcher = ExampleMatcher.matching()                 //构建匹配器
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)    //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);                                         //改变默认大小写忽略方式：忽略大小写

        Comment temp = new Comment();
        temp.setNickname("游客A");
        Example<Comment> pageExample = Example.of(temp, pageMatcher);           //创建实例
        Page<Comment> pages = userRepository.findAll(pageExample, pageable);    //分页查询
        System.out.println("总页数:"+pages.getTotalPages());
        System.out.println("数据列表:"+pages.getContent());
        System.out.println("是否有下一页:"+pages.hasNext());
        System.out.println("========== 分页查询 END ============");

    }



    /* SpringData规范查询数据 */
    @RequestMapping("data")
    public void springData(){

        Comment info = userRepository.findByContentsAndLikenum("要学习知识", 100);
        System.out.println(info);

        List<Comment> infoList = userRepository.readAllByUserid("dmbjz");
        infoList.forEach(System.out::println);

    }




}
